package com.superlz.demo.security.web.async;

import org.apache.commons.lang.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.concurrent.Callable;

/**
 * 异步处理REST请求
 *
 * 两种方式：
 * 1.使用Runnable异步处理Rest服务
 * 2.使用DeferredResult异步处理Rest服务
 *
 * 异步处理的配置拦截：WebConfig
 */
@RestController
public class AsyncController {
	
	@Autowired
	private MockQueue mockQueue;
	
	@Autowired
	private DeferredResultHolder deferredResultHolder;
	
	private Logger logger = LoggerFactory.getLogger(getClass());

	@RequestMapping("/order1")
	public Callable<String> order1() throws Exception {
		// 可通过该日志查看 线程情况和时间
		logger.info("主线程开始");

		// lz: 使用Runnable异步处理Rest服务,依赖于主线程
		Callable<String> result = new Callable<String>() {
			@Override
			public String call() throws Exception {
				logger.info("副线程开始");
				Thread.sleep(1000);
				logger.info("副线程返回");
				return "success";
			}
		};
		logger.info("主线程结束");
		return result;
	}
	
	@RequestMapping("/order2")
	public DeferredResult<String> order2() throws Exception {
		// 可通过该日志查看 线程情况和时间
		logger.info("主线程开始");

		// 模拟mq，异步下单，使用deferredResultHolder存储信息，用于多线程的消息通讯
		String orderNumber = RandomStringUtils.randomNumeric(8);
		mockQueue.setPlaceOrder(orderNumber);
		
		DeferredResult<String> result = new DeferredResult<>();
		deferredResultHolder.getMap().put(orderNumber, result);
		
		return result;
	}

}
